package com.geek.web;

import com.geek.po.Blog;
import com.geek.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.ArrayList;
import java.util.List;

@Controller
public class BlogController {

    protected final static int PageBreak = 5;

    @Autowired
    private BlogService blogService;

    @GetMapping("/")
    public String home(@PageableDefault(size = BlogController.PageBreak, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable, Model model) {
        long blogTotal = blogService.countBlog();
        int pageNumber = pageable.getPageNumber();
        long pageCount = 0;

        long rem = blogTotal % BlogController.PageBreak;
        if (rem == 0) {
            pageCount = blogTotal / BlogController.PageBreak;
        } else {
            pageCount = (blogTotal - rem) / BlogController.PageBreak + 1;
        }

        if ((pageNumber + 1) > pageCount || pageNumber < 0) {
            model.addAttribute("message", "哦吼，没有找到当前页面的博客信息哦！");
            return "404";
        }

        pageNumber++;

        model.addAttribute("blogs", blogService.listBlog(pageable));
        model.addAttribute("blogTotal", blogTotal);
        model.addAttribute("currentPage", pageNumber);
        model.addAttribute("pageCount", pageCount);

        List<Integer> navigators = new ArrayList<Integer>();

        if (pageNumber - 1 > 0) {
            if (pageNumber - 2 > 0 && pageNumber == pageCount) {
                navigators.add(pageNumber - 2);
            }
            navigators.add(pageNumber - 1);
        }

        navigators.add(pageNumber);


        if (pageNumber + 1 <= pageCount) {
            navigators.add(pageNumber + 1);
            if (pageNumber + 2 < pageCount && pageNumber == 1) {
                navigators.add(pageNumber + 2);
            }
        }

        model.addAttribute("navigators", navigators);
        model.addAttribute("recommendBlogTop", blogService.listRecommendBlogTop(15));
        return "home";
    }

    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id, Model model) {
        Blog blog = blogService.getBlog(id);
        if (blog == null) {
            model.addAttribute("message", "哦吼，没有找到当前的博客记录哦！");
            return "404";
        }
        model.addAttribute("blog", blog);
        blog.addView();

        blogService.saveBlog(blog);
        return "blog";
    }

}
